from collections import defaultdict
from datetime import datetime

from flask import request, jsonify
from flask_restx import Namespace, Resource, fields
from flask_jwt_extended import jwt_required
from sqlalchemy import and_

# 导入 tb_alarm 模型
from app1.models import Zbfwb_kms_alarm
from app1 import db
from app1 import api

from app1.customdate import CustomDate
from app1.utils import format_response, format_response_page

# 创建 Flask-RESTx 命名空间
ns_kms_alarm = Namespace('nskmsalarm', description='Kms Alarm operations')

# 使用 Flask-RESTx
kms_alarm_model = ns_kms_alarm.model(
    'kms_alarm',
    {
        "seq_num": fields.String(description='告警序号'),
        "occurrence_time": CustomDate(dt_format='str_time', description='告警发生时间'),
        "sys_name": fields.String(description='系统名称'),
        "service_catalog": fields.String(description='服务目录编号'),
        "dev_addr": fields.String(description='IP地址'),
        "info": fields.String(description='告警内容'),
        "keyword": fields.String(description='关键字'),
        "repeat_times": fields.Integer(description='重复次'),
        "level": fields.String(description='告警级别'),
        "status": fields.Integer(description='状态（0未处置，1已处置）'),
        "kms_count": fields.Integer(description='知识匹配计数'),
        "kms_id": fields.Integer(description='知识ID'),
        "is_change_related": fields.Integer(description='是否变更引起（0否、1是）'),
        "is_report": fields.Integer(description='是否举手（0否、1是）'),
        "actual_cause": fields.String(description='实际原因'),
        "action_type": fields.String(description='处置类别（0无需处置、1 值班处置、2二线处置）'),
        "action": fields.String(description='处置类别（0无需处置、1 值班处置、2二线处置）'),
        "create_by": fields.String(description='创建者'),
        "create_time": CustomDate(dt_format='str_time', description='创建时间'),
        "update_by": fields.String(description='更新者'),
        "update_time": CustomDate(dt_format='str_time', description='更新时间'),
        "remark": fields.String(description='备注'),
    }
)

# model 增加一个id作为输出时候的自增序号，从1开始
kms_alarm_withid_model = ns_kms_alarm.model(
    'kms_alarm_withid',
    {
        "id": fields.Integer(description='自增序号'),
        "seq_num": fields.String(description='告警序号'),
        "occurrence_time": CustomDate(dt_format='str_time', description='告警发生时间'),
        "sys_name": fields.String(description='系统名称'),
        "service_catalog": fields.String(description='服务目录编号'),
        "dev_addr": fields.String(description='IP地址'),
        "info": fields.String(description='告警内容'),
        "keyword": fields.String(description='关键字'),
        "repeat_times": fields.Integer(description='重复次'),
        "level": fields.String(description='告警级别'),
        "status": fields.Integer(description='状态（0未处置，1已处置）'),
        "kms_count": fields.Integer(description='知识匹配计数'),
        "kms_id": fields.Integer(description='知识ID'),
        "is_change_related": fields.Integer(description='是否变更引起（0否、1是）'),
        "is_report": fields.Integer(description='是否举手（0否、1是）'),
        "actual_cause": fields.String(description='实际原因'),
        "action_type": fields.String(description='处置类别（0无需处置、1 值班处置、2二线处置）'),
        "action": fields.String(description='处置类别（0无需处置、1 值班处置、2二线处置）'),
        "create_by": fields.String(description='创建者'),
        "create_time": CustomDate(dt_format='str_time', description='创建时间'),
        "update_by": fields.String(description='更新者'),
        "update_time": CustomDate(dt_format='str_time', description='更新时间'),
        "remark": fields.String(description='备注'),
    }
)

# 定义外层的响应模型
response_model = ns_kms_alarm.model('Response_detail', {
    'message': fields.Nested(ns_kms_alarm.model('Message_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Nested(kms_alarm_model))
    }))
})

kms_alarm_sys_sts_model = ns_kms_alarm.model(
    'kms_alarm_sys_sts',
    {
        "sys_name": fields.String(description='系统名称'),
        "level": fields.Nested(ns_kms_alarm.model('levels', {
            "WARNING": fields.Integer,
            "MINOR": fields.Integer,
            "MAJOR": fields.Integer,
            "INFO": fields.Integer,
            "CRITICAL": fields.Integer,
        }))
    }
)

# 定义外层的响应模型，按系统分类
response_sys_model = ns_kms_alarm.model('Response_sys', {
    'message': fields.Nested(ns_kms_alarm.model('Message_sys_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Nested(kms_alarm_sys_sts_model))
    }))
})

kms_alarm_level_sys_sts_model = ns_kms_alarm.model('kms_alarm_level_sys_sts', {
    "sys_name": fields.String,
    "count": fields.Integer
})

kms_alarm_level_sts_model = ns_kms_alarm.model('kms_alarm_level_sts', {
    "level": fields.Nested(ns_kms_alarm.model('levels', {
        "WARNING": fields.List(fields.Nested(kms_alarm_level_sys_sts_model)),
        "MINOR": fields.List(fields.Nested(kms_alarm_level_sys_sts_model)),
        "MAJOR": fields.List(fields.Nested(kms_alarm_level_sys_sts_model)),
        "INFO": fields.List(fields.Nested(kms_alarm_level_sys_sts_model)),
        "CRITICAL": fields.List(fields.Nested(kms_alarm_level_sys_sts_model)),
    })
                           )
})

kms_alarm_level_sys2_model = ns_kms_alarm.model('kms_alarm_level2_sts', {
    "level2": fields.List(fields.Raw),  # 不固定格式
    "fields": fields.List(fields.String)
})

# 定义外层的响应模型1，按告警级别分类
response_level_model = ns_kms_alarm.model('Response_level', {
    'message': fields.Nested(ns_kms_alarm.model('Message_level_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.Nested(kms_alarm_level_sts_model)
    }))
})

# 定义外层的响应模型2，按告警级别分类
response_level2_model = ns_kms_alarm.model('Response_level2', {
    'message': fields.Nested(ns_kms_alarm.model('Message_level_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.Nested(kms_alarm_level_sys2_model)
    }))
})

# 定义外层的响应模型3，按告警级别分类
response_level3_model = ns_kms_alarm.model('Response_level3', {
    'message': fields.Nested(ns_kms_alarm.model('Message_level_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.List(fields.Raw))
    }))
})

# 定义外层的响应模型3，按告警级别分类
response_type_sts_model = ns_kms_alarm.model('Response_type_sts', {
    'message': fields.Nested(ns_kms_alarm.model('Message_type_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Raw)
    }))
})

# 数据示例
# data:[ ['ADPS','AMLMAS-D-AEA','AIAP','CICP'],
# ['WARNING','MINOR',"MAJOR','INFO','OTHERS'],
# [15,8,0, 0, 12,'ADPS','2024-06-01'],
# [15,8,0, 0, 12,'ADPS','2024-06-02'],
# [15,8,0, 0, 12,'ADPS','2024-06-03'],
# [83.1,73.4,55.1, 1, 34,'AMLMAS-D-AEA','2024-06-01'],
# [83.1,73.4,55.1, 1, 34,'AMLMAS-D-AEA','2024-06-02'],
# [83.1,73.4,55.1, 1, 34,'AMLMAS-D-AEA','2024-06-03'],
# [86.4,65.2,82.5,23,4,'AIAP','2024-06-01'],
# [86.4,65.2,82.5,23,4,'AIAP','2024-06-02'],
# [86.4,65.2,82.5,23,4,'AIAP','2024-06-03'],
# [72.4,53.9,39.1, 5,7,'CICP','2024-06-01'],
# [72.4,53.9,39.1, 5,7,'CICP','2024-06-02'],
# [72.4,53.9,39.1, 5,7,'CICP','2024-06-03'],
# ]

# # 定义告警级别和系统统计的模型
# kms_alarm_sys_trend1_sts_model = ns_kms_alarm.model('kms_alarm_sys_trend1_sts', {
#     "product": fields.String,
#     "WARNING": fields.Integer,
#     "MINOR": fields.Integer,
#     "MAJOR": fields.Integer,
#     "INFO": fields.Integer,
#     "OTHERS": fields.Integer,
#     "date": fields.String
# })

# 定义外层的响应模型trend1，按告警级别分类
response_trend1_model = ns_kms_alarm.model('Response_trend1', {
    'message': fields.Nested(ns_kms_alarm.model('Message_trend1_detail', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.List(fields.Raw))  # data 是一个列表的列表
    }))
})

kms_alarm_seq_model = ns_kms_alarm.model('kms_alarm_seq_num', {
    "seq_num": fields.String(description='告警序号'),
})

kms_alarm_sys_name_model = ns_kms_alarm.model('kms_alarm_sys_name', {
    "sys_name": fields.String(description='系统名称'),
})

kms_alarm_dev_addr_model = ns_kms_alarm.model('kms_alarm_dev_addr', {
    "dev_addr": fields.String(description='IP地址'),
})

kms_alarm_rptimes_addr_model = ns_kms_alarm.model('kms_alarm_rptimes_addr', {
    "repeat_times": fields.String(description='重复次数'),
})

kms_alarm_level_addr_model = ns_kms_alarm.model('kms_alarm_level_addr', {
    "level": fields.String(description='告警级别'),
})

ksm_alarm_page_model = ns_kms_alarm.model('kms_alarm_page', {
    'page': fields.Integer(required=False, description='start page', default=1),
    'per_page': fields.Integer(required=False, description='per page', default=20),
    'max_page': fields.Integer(required=False, description='max page', default=50),
})

ksm_alarm_page_field_model = ns_kms_alarm.model('kms_alarm_page_field', {
    "sys_name": fields.String(description='系统名称', default=""),
    "dev_addr": fields.String(description='IP地址', default=""),
    "repeat_times": fields.String(description='重复次数', default=""),
    "level": fields.String(description='告警级别', default=""),
    'page': fields.Integer(required=False, description='start page', default=1),
    'per_page': fields.Integer(required=False, description='per page', default=20),
    'max_page': fields.Integer(required=False, description='max page', default=50),
})

kms_alarm_type_sts_model = ns_kms_alarm.model('kms_alarm_type_sts', {
    "type": fields.String(description='统计类型'),
    'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
})

ksm_alarm_page_fields_model = ns_kms_alarm.model('kms_alarm_page_fields', {
    "sys_name": fields.List(fields.String, description='系统名称', default=[]),
    "dev_addr": fields.List(fields.String, description='IP地址', default=[]),
    "repeat_times": fields.List(fields.String, description='重复次数', default=[]),
    "level": fields.List(fields.String, description='告警级别', default=[]),
    'page': fields.Integer(required=False, description='start page', default=1),
    'per_page': fields.Integer(required=False, description='per page', default=20),
    'max_page': fields.Integer(required=False, description='max page', default=50),
})

# 定义输入模型
ksm_alarm_page_fields_date_model = ns_kms_alarm.model('kms_alarm_page_fields_date', {
    "sys_name": fields.List(fields.String, description='系统名称', default=[]),
    "dev_addr": fields.List(fields.String, description='IP地址', default=[]),
    "repeat_times": fields.List(fields.String, description='重复次数', default=[]),
    "level": fields.List(fields.String, description='告警级别', default=[]),
    'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    'page': fields.Integer(required=False, description='start page', default=1),
    'per_page': fields.Integer(required=False, description='per page', default=20),
    'max_page': fields.Integer(required=False, description='max page', default=50),
})

ksm_alarm_page_fields_date_info_model = ns_kms_alarm.model('kms_alarm_page_fields_date_info', {
    "sys_name": fields.List(fields.String, description='系统名称', default=[]),
    "dev_addr": fields.List(fields.String, description='IP地址', default=[]),
    "repeat_times": fields.List(fields.String, description='重复次数', default=[]),
    "level": fields.List(fields.String, description='告警级别', default=[]),
    "info": fields.List(fields.String, description='告警内容', default=[]),
    'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    'pageNo': fields.Integer(required=False, description='start page', default=1),
    'pageSize': fields.Integer(required=False, description='per page', default=20),
    'max_page': fields.Integer(required=False, description='max page', default=50),
})

# 输入格式
# {
#   "sys_name": "",
#   "dev_addr": "",
#   "repeat_times": "",
#   "level": "",
#   "start_date": "2024-06-18 18:01:40.000000",
#   "end_date": "2024-06-19 18:01:40.000000"
# }

# kms_alarm_multi_query_model = ns_kms_alarm.model(
#     'kms_alarm_multi_query',
#     {
#         "sys_name": fields.String(description='系统名称', default=""),
#         "dev_addr": fields.String(description='IP地址', default=""),
#         "repeat_times": fields.String(description='重复次数', default=""),
#         "level": fields.String(description='告警级别', default=""),
#         # 'start_date': CustomDate(dt_format='str_time',),
#         'start_date': fields.DateTime(dt_format='iso8601', default=str(datetime.now().isoformat())),
#         # 'end_date': CustomDate(dt_format='str_time'),
#         'end_date': fields.DateTime(dt_format='iso8601', default=str(datetime.now().isoformat())),
#     }
# )

kms_alarm_multi_query_model = ns_kms_alarm.model(
    'kms_alarm_multi_query',
    {
        "sys_name": fields.String(description='系统名称', default=""),
        "dev_addr": fields.String(description='IP地址', default=""),
        "repeat_times": fields.String(description='重复次数', default=""),
        "level": fields.String(description='告警级别', default=""),
        'start_date': fields.String(description='开始日期，格式：YYYY-MM-DD HH:MM:SS',
                                    default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
        'end_date': fields.String(description='结束日期，格式：YYYY-MM-DD HH:MM:SS',
                                  default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    }
)

# kms_alarm_multi_sys_query_model = ns_kms_alarm.model(
#     'kms_alarm_multi_sys_query',
#     {
#         "sys_name": fields.List(fields.String, description='系统名称', default=[]),
#         "dev_addr": fields.String(description='IP地址', default=""),
#         "repeat_times": fields.String(description='重复次数', default=""),
#         "level": fields.String(description='告警级别', default=""),
#         'start_date': fields.DateTime(dt_format='iso8601', default=str(datetime.now().isoformat())),
#         'end_date': fields.DateTime(dt_format='iso8601', default=str(datetime.now().isoformat())),
#     }
# )

kms_alarm_multi_sys_query_model = ns_kms_alarm.model(
    'kms_alarm_multi_sys_query',
    {
        "sys_name": fields.List(fields.String, description='系统名称', default=[]),
        "dev_addr": fields.String(description='IP地址', default=""),
        "repeat_times": fields.String(description='重复次数', default=""),
        "level": fields.String(description='告警级别', default=""),
        'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
        'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    }
)

kms_alarm_multi_sys_query1_model = ns_kms_alarm.model(
    'kms_alarm_multi_sys_query1',
    {
        "sys_name": fields.List(fields.String, description='系统名称', default=[]),
        "dev_addr": fields.List(fields.String, description='IP地址', default=[]),
        "repeat_times": fields.List(fields.String, description='重复次数', default=[]),
        "level": fields.List(fields.String, description='告警级别', default=[]),
        'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
        'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    }
)

kms_alarm_page_data_model = ns_kms_alarm.model('kms_alarm_pagedata', {
    'has_next': fields.Boolean(),  # has_next: 是否还有下一页
    'has_prev': fields.Boolean(),  # has_prev: 是否还有上一页
    'items': fields.List(fields.Nested(kms_alarm_model)),  # items: 返回当前页的所有内容
    'next': fields.List(fields.Nested(kms_alarm_model)),  # next(error_out=False): 返回下一页的Pagination对象
    'prev': fields.List(fields.Nested(kms_alarm_model)),  # prev(error_out=False): 返回上一页的Pagination对象
    'page': fields.Integer(),  # page: 当前页的页码(从1开始)
    'pages': fields.Integer(),  # pages: 总页数
    'per_page': fields.Integer(),  # per_page: 每页显示的数量
    'prev_num': fields.Integer(),  # prev_num: 上一页页码数
    'next_num': fields.Integer(),  # next_num: 下一页页码数
    # query: 返回
    'total': fields.Integer()  # total: 查询返回的记录总数
})

kms_alarm_page_data_1_model = ns_kms_alarm.model('kms_alarm_pagedata_1', {
    'has_next': fields.Boolean(),  # has_next: 是否还有下一页
    'has_prev': fields.Boolean(),  # has_prev: 是否还有上一页
    'data': fields.List(fields.Nested(kms_alarm_model)),  # items: 返回当前页的所有内容
    'next': fields.List(fields.Nested(kms_alarm_model)),  # next(error_out=False): 返回下一页的Pagination对象
    'prev': fields.List(fields.Nested(kms_alarm_model)),  # prev(error_out=False): 返回上一页的Pagination对象
    'pageNo': fields.Integer(),  # page: 当前页的页码(从1开始)
    'totalPage': fields.Integer(),  # pages: 总页数
    'pageSize': fields.Integer(),  # per_page: 每页显示的数量
    'prev_num': fields.Integer(),  # prev_num: 上一页页码数
    'next_num': fields.Integer(),  # next_num: 下一页页码数
    # query: 返回
    'totalCount': fields.Integer()  # total: 查询返回的记录总数
})

# 定义外层的响应翻页返回
response_page_data_1_model = ns_kms_alarm.model('Response_page_data_1', {
    "message": fields.String(description='翻页查询结果'),
    "result": fields.Nested(kms_alarm_page_data_1_model),
    "status": fields.Integer(description='返回状态', default=200),  # 查询返回状态,
    "timestamp": fields.String(description='时间戳', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),  # 时间戳
})

kms_alarm_page_withid_data_1_model = ns_kms_alarm.model('kms_alarm_page_withiddata_1', {
    'has_next': fields.Boolean(),  # has_next: 是否还有下一页
    'has_prev': fields.Boolean(),  # has_prev: 是否还有上一页
    'data': fields.List(fields.Nested(kms_alarm_withid_model)),  # items: 返回当前页的所有内容
    'next': fields.List(fields.Nested(kms_alarm_withid_model)),  # next(error_out=False): 返回下一页的Pagination对象
    'prev': fields.List(fields.Nested(kms_alarm_withid_model)),  # prev(error_out=False): 返回上一页的Pagination对象
    'pageNo': fields.Integer(),  # page: 当前页的页码(从1开始)
    'totalPage': fields.Integer(),  # pages: 总页数
    'pageSize': fields.Integer(),  # per_page: 每页显示的数量
    'prev_num': fields.Integer(),  # prev_num: 上一页页码数
    'next_num': fields.Integer(),  # next_num: 下一页页码数
    # query: 返回
    'totalCount': fields.Integer()  # total: 查询返回的记录总数
})

# 定义外层的响应翻页返回带id
response_page_withid_data_1_model = ns_kms_alarm.model('Response_page_withid_data_1', {
    "message": fields.String(description='翻页查询结果'),
    "result": fields.Nested(kms_alarm_page_withid_data_1_model),
    "status": fields.Integer(description='返回状态', default=200),  # 查询返回状态,
    "timestamp": fields.String(description='时间戳', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),  # 时间戳
})

# for dashboard
kms_alarm_dashboard_query_model = ns_kms_alarm.model(
    'kms_alarm_dashboard_query',
    {
        "sys_name": fields.List(fields.String, description='系统名称', default=[]),
        "dev_addr": fields.List(fields.String, description='IP地址', default=[]),
        "repeat_times": fields.List(fields.String, description='重复次数', default=[]),
        "level": fields.List(fields.String, description='告警级别', default=[]),
        'start_date': fields.String(description='开始日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
        'end_date': fields.String(description='结束日期', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),
    }
)

kms_alarm_dashboard_level_model = ns_kms_alarm.model(
    'kms_alarm_dashboard_level',
    {
        'xAxis': fields.Nested(ns_kms_alarm.model('xAxis', {
            "type": fields.String(description='数据类型', default='category'),
            "data": fields.List(fields.String, description='告警类别',
                                default=["CRITICAL", "MINOR", "MAJOR", "WARNING", "INFO"]),
        })),
        'yAxis': fields.Nested(ns_kms_alarm.model('yAxis', {
            "type": fields.String(description='数据类型', default='value'),
        })),
        'series': fields.Nested(ns_kms_alarm.model('series', {
            "data": fields.List(fields.String, description='告警数量', default=[]),
            "type": fields.String(description='数据类型', default='bar'),
        })),
    }
)

# 定义外层的响应模型trend1，按告警级别分类
response_dashboard_level_model = ns_kms_alarm.model('Response_dashboard_level', {
    'message': fields.Nested(ns_kms_alarm.model('Message_dashboard_level', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.Nested(kms_alarm_dashboard_level_model)  # data 是一个列表的列表
    }))
})

# 输出：按照系统数量统计
kms_alarm_dashboard_app_model = ns_kms_alarm.model(
    'kms_alarm_dashboard_level',
    {
        'xAxis': fields.Nested(ns_kms_alarm.model('xAxis', {
            "type": fields.String(description='数据类型', default='category'),
            "data": fields.List(fields.String, description='应用系统',
                                default=[]),
        })),
        'yAxis': fields.Nested(ns_kms_alarm.model('yAxis', {
            "type": fields.String(description='数据类型', default='value'),
        })),
        'series': fields.Nested(ns_kms_alarm.model('series', {
            "data": fields.List(fields.String, description='应用系统数量', default=[]),
            "type": fields.String(description='数据类型', default='bar'),
        })),
    }
)

# 定义外层的响应模型trend1，按告警级别分类
response_dashboard_app_model = ns_kms_alarm.model('Response_dashboard_level', {
    'message': fields.Nested(ns_kms_alarm.model('Message_dashboard_level', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.Nested(kms_alarm_dashboard_app_model)  # data 是一个列表的列表
    }))
})


@ns_kms_alarm.route('/getbyseq')
class AlarmSeqResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_seq_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_model)
    def post(self):
        """以告警序号取告警列表"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        seqnum = sysdata['seq_num']

        kms_alarm = Zbfwb_kms_alarm.query.filter_by(seq_num=seqnum).all()

        # print(kms_alarm)
        if kms_alarm:
            return kms_alarm
        api.abort(404, f"alarm {seqnum} not found")


@ns_kms_alarm.route('/getbysysname')
class AlarmSysNameResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_sys_name_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_model)
    def post(self):
        """以系统名获取告警列表"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        sysname = sysdata['sys_name']

        kms_alarm = Zbfwb_kms_alarm.query.filter_by(sys_name=sysname).all()

        total_count = len(kms_alarm)

        print("total:" + str(total_count))

        # print(kms_alarm)
        if kms_alarm:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(kms_alarm, total_count)
            return response_data
        api.abort(404, f"alarm {sysname} not found")


@ns_kms_alarm.route('/getbydevaddr')
class AlarmDevAddrResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_dev_addr_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_model)
    def post(self):
        """以设备ip地址获取告警列表"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        devaddr = sysdata['dev_addr']

        kms_alarm = Zbfwb_kms_alarm.query.filter_by(dev_addr=devaddr).all()

        # print(kms_alarm)
        if kms_alarm:
            return kms_alarm
        api.abort(404, f"alarm {devaddr} not found")


@ns_kms_alarm.route('/getbyrptimes')
class AlarmRpTimesResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_rptimes_addr_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_model)
    def post(self):
        """以告警次数获取告警列表"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        repeattimes = sysdata['repeat_times']

        kms_alarm = Zbfwb_kms_alarm.query.filter_by(repeat_times=repeattimes).all()

        # print(kms_alarm)
        if kms_alarm:
            return kms_alarm
        api.abort(404, f"alarm {repeattimes} not found")


@ns_kms_alarm.route('/getbylevel')
class AlarmLevelResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_level_addr_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_model)
    def post(self):
        """以告警等级获取告警列表"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        level = sysdata['level']

        kms_alarm = Zbfwb_kms_alarm.query.filter_by(level=level).all()

        # print(kms_alarm)
        if kms_alarm:
            return kms_alarm
        api.abort(404, f"alarm {level} not found")


@ns_kms_alarm.route('/kmsalarmpage')
class AlarmKmsPageResource(Resource):
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_page_data_model)
    @ns_kms_alarm.expect(ksm_alarm_page_model)
    def post(self):
        """分页获取告警列表"""  # 接口说明紧跟在函数后面
        pagedata = api.payload

        # 获取分页请求信息
        page = pagedata['page']
        if page < 1:
            # default start page
            page = 1
        per_page = pagedata['per_page']
        if per_page < 1:
            # default per page
            per_page = 10

        error_out = False
        # 最大页数
        max_per_page = pagedata['max_page']

        # query
        pagealarms = Zbfwb_kms_alarm.query.paginate(page=page, per_page=per_page, error_out=error_out,
                                                    max_per_page=max_per_page)

        # has_next: 是否还有下一页
        # has_prev: 是否还有上一页
        # items: 返回当前页的所有内容
        # next(error_out=False): 返回下一页的Pagination对象
        # prev(error_out=False): 返回上一页的Pagination对象
        # page: 当前页的页码(从1开始)
        # pages: 总页数
        # per_page: 每页显示的数量
        # prev_num: 上一页页码数
        # next_num: 下一页页码数
        # query: 返回
        # total: 查询返回的记录总

        return pagealarms, 200


@ns_kms_alarm.route('/kmsalarmpagefield')
class AlarmKmsPageFieldResource(Resource):
    @ns_kms_alarm.marshal_with(kms_alarm_page_data_model)
    @ns_kms_alarm.expect(ksm_alarm_page_field_model)
    def post(self):
        """分页获取告警列表"""
        pagedata = api.payload

        # 获取分页请求信息
        page = pagedata.get('page', 1)
        per_page = pagedata.get('per_page', 20)
        max_per_page = pagedata.get('max_page', 50)

        # 获取查询条件
        sys_name = pagedata.get('sys_name', "")
        dev_addr = pagedata.get('dev_addr', "")
        repeat_times = pagedata.get('repeat_times', "")
        level = pagedata.get('level', "")

        # 构建查询过滤条件
        filters = []
        if sys_name:
            filters.append(Zbfwb_kms_alarm.sys_name == sys_name)
        if dev_addr:
            filters.append(Zbfwb_kms_alarm.dev_addr == dev_addr)
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeat_times)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)

        # 执行查询和分页
        query = Zbfwb_kms_alarm.query.filter(*filters)
        pagealarms = query.paginate(page=page, per_page=per_page, error_out=False, max_per_page=max_per_page)

        # 返回分页结果
        return pagealarms, 200


@ns_kms_alarm.route('/kmsalarmpagefields')
class AlarmKmsPageFieldsResource(Resource):
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_page_data_model)
    @ns_kms_alarm.expect(ksm_alarm_page_fields_model)
    def post(self):
        """分页获取告警列表"""
        pagedata = api.payload

        # 获取分页请求信息
        page = pagedata.get('page', 1)
        if page < 1:
            page = 1

        per_page = pagedata.get('per_page', 20)
        if per_page < 1:
            per_page = 10

        max_per_page = pagedata.get('max_page', 50)

        # 获取查询条件
        sys_names = pagedata.get('sys_name', [])
        dev_addrs = pagedata.get('dev_addr', [])
        repeat_times = pagedata.get('repeat_times', [])
        levels = pagedata.get('level', [])

        # 构建查询条件
        filters = []
        if sys_names:
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
        if dev_addrs:
            filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))
        if levels:
            filters.append(Zbfwb_kms_alarm.level.in_(levels))

        # 查询数据库
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))
        pagealarms = query.paginate(page=page, per_page=per_page, error_out=False, max_per_page=max_per_page)

        # 返回分页结果
        return pagealarms, 200


@ns_kms_alarm.route('/kmsalarmpagefieldsdate')
class AlarmKmsPageFieldsdateResource(Resource):
    # @jwt_required()
    @ns_kms_alarm.marshal_with(kms_alarm_page_data_model)
    @ns_kms_alarm.expect(ksm_alarm_page_fields_date_model)
    def post(self):
        """分页获取告警列表"""  # 接口说明紧跟在函数后面
        pagedata = api.payload

        # 获取分页请求信息
        page = pagedata.get('page', 1)
        if page < 1:
            page = 1
        per_page = pagedata.get('per_page', 20)
        if per_page < 1:
            per_page = 10
        max_per_page = pagedata.get('max_page', 50)

        # 日期格式处理
        start_date_str = pagedata.get('start_date', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        end_date_str = pagedata.get('end_date', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]

        sys_names = pagedata.get('sys_name', [])
        dev_addrs = pagedata.get('dev_addr', [])
        repeat_times = pagedata.get('repeat_times', [])
        levels = pagedata.get('level', [])

        if sys_names:
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
        if dev_addrs:
            filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))
        if levels:
            filters.append(Zbfwb_kms_alarm.level.in_(levels))

        # 查询并获取记录
        pagealarms = Zbfwb_kms_alarm.query.filter(and_(*filters)).paginate(
            page=page, per_page=per_page, error_out=False, max_per_page=max_per_page
        )

        return pagealarms, 200


@ns_kms_alarm.route('/kmsalarmpagefieldsdateinfo')
class AlarmKmsPageFieldsdateinfoResource(Resource):
    @ns_kms_alarm.marshal_with(kms_alarm_page_data_model)
    @ns_kms_alarm.expect(ksm_alarm_page_fields_date_info_model)
    def post(self):
        """分页获取告警列表"""
        pagedata = api.payload

        # 获取分页请求信息
        # page = pagedata['page']
        page = pagedata['pageNo']
        if page < 1:
            page = 1
        # per_page = pagedata['per_page']
        per_page = pagedata['pageSize']
        if per_page < 1:
            per_page = 10
        error_out = False
        max_per_page = pagedata['max_page']

        # 构建查询条件
        filters = []

        # 处理 sys_name 字段
        sys_names = pagedata.get('sys_name', [])
        if sys_names:
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))

        # 处理 dev_addr 字段
        dev_addrs = pagedata.get('dev_addr', [])
        if dev_addrs:
            filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))

        # 处理 repeat_times 字段
        repeat_times = pagedata.get('repeat_times', [])
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))

        # 处理 level 字段
        levels = pagedata.get('level', [])
        if levels:
            filters.append(Zbfwb_kms_alarm.level.in_(levels))

        # 处理 info 字段
        info_conditions = pagedata.get('info', [])
        if info_conditions:
            for condition in info_conditions:
                filters.append(Zbfwb_kms_alarm.info.op('regexp')(condition))

        # 处理时间范围
        start_date_str = pagedata['start_date']
        end_date_str = pagedata['end_date']
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')
        filters.append(Zbfwb_kms_alarm.occurrence_time >= start_date)
        filters.append(Zbfwb_kms_alarm.occurrence_time <= end_date)

        # 执行查询并分页
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))
        pagealarms = query.paginate(page=page, per_page=per_page, error_out=error_out, max_per_page=max_per_page)

        return pagealarms, 200


@ns_kms_alarm.route('/kmsalarmpagefieldsdateinfo1')
class AlarmKmsPageFieldsdateinfo1Resource(Resource):
    @ns_kms_alarm.marshal_with(response_page_data_1_model)
    @ns_kms_alarm.expect(ksm_alarm_page_fields_date_info_model)
    def post(self):
        """分页获取告警列表"""
        pagedata = api.payload

        try:
            # 获取分页请求信息
            # page = pagedata['page']
            page = pagedata['pageNo']
            if page < 1:
                page = 1

            # per_page = pagedata['per_page']
            per_page = pagedata['pageSize']
            if per_page < 1:
                per_page = 10

            max_per_page = pagedata['max_page']
            error_out = False

            # 构建查询条件
            query = Zbfwb_kms_alarm.query

            # 添加各个条件查询
            if pagedata.get('sys_name'):
                query = query.filter(Zbfwb_kms_alarm.sys_name.in_(pagedata['sys_name']))
            if pagedata.get('dev_addr'):
                query = query.filter(Zbfwb_kms_alarm.dev_addr.in_(pagedata['dev_addr']))
            if pagedata.get('repeat_times'):
                query = query.filter(Zbfwb_kms_alarm.repeat_times.in_(pagedata['repeat_times']))
            if pagedata.get('level'):
                query = query.filter(Zbfwb_kms_alarm.level.in_(pagedata['level']))
            if pagedata.get('info'):
                for info_value in pagedata['info']:
                    query = query.filter(Zbfwb_kms_alarm.info.like(f"%{info_value}%"))

            # 添加日期范围查询条件
            start_date = datetime.strptime(pagedata['start_date'], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(pagedata['end_date'], '%Y-%m-%d %H:%M:%S')

            query = query.filter(Zbfwb_kms_alarm.occurrence_time >= start_date)
            query = query.filter(Zbfwb_kms_alarm.occurrence_time <= end_date)

            # 分页查询
            pagealarms = query.paginate(page=page, per_page=per_page, error_out=error_out, max_per_page=max_per_page)

            # 构建分页结果
            result = {
                'has_next': pagealarms.has_next,
                'has_prev': pagealarms.has_prev,
                'data': [alarm.to_dict() for alarm in pagealarms.items],
                'next': pagealarms.next(error_out=False).items if pagealarms.has_next else [],
                'prev': pagealarms.prev(error_out=False).items if pagealarms.has_prev else [],
                'pageNo': pagealarms.page,
                'totalPage': pagealarms.pages,
                'pageSize': pagealarms.per_page,
                'prev_num': pagealarms.prev_num,
                'next_num': pagealarms.next_num,
                'totalCount': pagealarms.total
            }

            # 使用 format_response_page 函数生成返回结果
            response = format_response_page(
                message="翻页查询结果",
                result=result,
                status=200,
                timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )

        except Exception as e:
            # 处理查询过程中可能出现的异常
            response = format_response_page(
                message=f"查询出错: {str(e)}",
                result=None,
                status=201,
                timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )

        return response


# 分页获取告警列表带id序号
@ns_kms_alarm.route('/kmsalarmpagefieldswithiddateinfo1')
class AlarmKmsPageFieldswithiddateinfo1Resource(Resource):
    @ns_kms_alarm.marshal_with(response_page_withid_data_1_model)
    @ns_kms_alarm.expect(ksm_alarm_page_fields_date_info_model)
    def post(self):
        """分页获取告警列表带id序号"""
        pagedata = api.payload

        try:
            # 获取分页请求信息
            page = pagedata['pageNo']
            if page < 1:
                page = 1

            per_page = pagedata['pageSize']
            if per_page < 1:
                per_page = 10

            max_per_page = pagedata['max_page']
            error_out = False

            # 构建查询条件
            query = Zbfwb_kms_alarm.query

            # 添加各个条件查询
            if pagedata.get('sys_name'):
                query = query.filter(Zbfwb_kms_alarm.sys_name.in_(pagedata['sys_name']))
            if pagedata.get('dev_addr'):
                query = query.filter(Zbfwb_kms_alarm.dev_addr.in_(pagedata['dev_addr']))
            if pagedata.get('repeat_times'):
                query = query.filter(Zbfwb_kms_alarm.repeat_times.in_(pagedata['repeat_times']))
            if pagedata.get('level'):
                query = query.filter(Zbfwb_kms_alarm.level.in_(pagedata['level']))
            if pagedata.get('info'):
                for info_value in pagedata['info']:
                    query = query.filter(Zbfwb_kms_alarm.info.like(f"%{info_value}%"))

            # 添加日期范围查询条件
            start_date = datetime.strptime(pagedata['start_date'], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(pagedata['end_date'], '%Y-%m-%d %H:%M:%S')

            query = query.filter(Zbfwb_kms_alarm.occurrence_time >= start_date)
            query = query.filter(Zbfwb_kms_alarm.occurrence_time <= end_date)

            # 分页查询
            pagealarms = query.paginate(page=page, per_page=per_page, error_out=error_out, max_per_page=max_per_page)

            # 构建分页结果，添加自增序号
            base_id = (page - 1) * per_page  # 根据分页计算当前页的起始序号
            data_with_id = [
                {"id": base_id + idx + 1, **alarm.to_dict()}  # 为每条记录添加自增 id
                for idx, alarm in enumerate(pagealarms.items)
            ]

            result = {
                'has_next': pagealarms.has_next,
                'has_prev': pagealarms.has_prev,
                'data': data_with_id,
                'next': pagealarms.next(error_out=False).items if pagealarms.has_next else [],
                'prev': pagealarms.prev(error_out=False).items if pagealarms.has_prev else [],
                'pageNo': pagealarms.page,
                'totalPage': pagealarms.pages,
                'pageSize': pagealarms.per_page,
                'prev_num': pagealarms.prev_num,
                'next_num': pagealarms.next_num,
                'totalCount': pagealarms.total
            }

            # 使用 format_response_page 函数生成返回结果
            response = format_response_page(
                message="翻页查询结果",
                result=result,
                status=200,
                timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )

        except Exception as e:
            # 处理查询过程中可能出现的异常
            response = format_response_page(
                message=f"查询出错: {str(e)}",
                result=None,
                status=201,
                timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )

        return response


@ns_kms_alarm.route('/getbymultiquery')
class AlarmMultiQResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_model)
    def post(self):
        """多条件查询告警列表 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        sysname = sysdata['sys_name']
        devaddr = sysdata['dev_addr']
        level = sysdata['level']
        repeattimes = sysdata['repeat_times']
        # 获取分页请求信息
        start_date_str = sysdata['start_date']
        end_date_str = sysdata['end_date']

        # 示例日期时间格式 2024-06-18 18:01:40.000000
        # 将日期字符串转换为 datetime 对象
        # start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
        # end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        kms_alarm = query.all()

        if kms_alarm:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(kms_alarm, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data

        # api.abort(404, f"alarm {level} not found")


@ns_kms_alarm.route('/getbymultiquerysys')
class AlarmMultiQSysResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_sys_model)
    def post(self):
        """多条件查询告警统计信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
        sysdata = api.payload

        sysname = sysdata['sys_name']
        devaddr = sysdata['dev_addr']
        level = sysdata['level']
        repeattimes = sysdata['repeat_times']
        # 获取分页请求信息
        start_date_str = sysdata['start_date']
        end_date_str = sysdata['end_date']

        # 示例日期时间格式 2024-06-18 18:01:40.000000
        # 将日期字符串转换为 datetime 对象
        # start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
        # end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # 初始化一个默认字典来存储每个系统名称及其告警级别统计信息
        sysname_dict = defaultdict(lambda: {"WARNING": 0, "MINOR": 0, "MAJOR": 0, "INFO": 0, "CRITICAL": 0})
        # 遍历 kms_alarm_model 数据并更新统计信息
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典
            # debug
            # print(alarm_dict["sys_name"])
            sys_name = alarm_dict["sys_name"]
            level = alarm_dict["level"]
            sysname_dict[sys_name][level] += 1

        # 将 sysname_dict 转换为所需的列表结构
        sysname_level = [{"sys_name": sys_name, "level": levels} for sys_name, levels in sysname_dict.items()]

        if sysname_level:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(sysname_level, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data

        # api.abort(404, f"alarm {level} not found")


@ns_kms_alarm.route('/getbymultiquerylevel')
class AlarmMultiQLevelResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_level_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
        leveldata = api.payload

        sysname = leveldata['sys_name']
        devaddr = leveldata['dev_addr']
        level = leveldata['level']
        repeattimes = leveldata['repeat_times']
        # 获取分页请求信息
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 示例日期时间格式 2024-06-18 18:01:40.000000
        # 将日期字符串转换为 datetime 对象
        # start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
        # end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # --------------------------------------------------#
        # # 初始化 level_sysname 字典结构
        # level_sysname = {
        #     "WARNING": defaultdict(int),
        #     "MINOR": defaultdict(int),
        #     "MAJOR": defaultdict(int),
        #     "INFO": defaultdict(int),
        #     "OTHERS": defaultdict(int)
        # }
        #
        # for alarm in kms_alarm:
        #     alarm_dict = alarm.to_dict()  # 将实例转换为字典
        #
        #     sys_name = alarm_dict["sys_name"]
        #     # print(sys_name)
        #     # level = alarm_dict["level"].lower()  # 将告警级别转换为小写
        #     # level = alarm_dict["level"]
        #     print(alarm_dict["level"].upper())
        #     level = alarm_dict["level"].upper()  # 将告警级别转换为小写
        #     level_sysname[level][sys_name] += 1
        #     # print(level_sysname[level][sys_name])
        #     print(level_sysname[level])
        # ------------------------------------------------------#

        # # 初始化 level_sysname 字典结构
        # level_sysname = {
        #     "WARNING": defaultdict(list),
        #     "MINOR": defaultdict(list),
        #     "MAJOR": defaultdict(list),
        #     "INFO": defaultdict(list),
        #     "OHTERS": defaultdict(list)
        # }

        # 初始化 level_sysname 字典结构
        level_sysname = {
            "level": {
                "WARNING": [],
                "MINOR": [],
                "MAJOR": [],
                "INFO": [],
                "OHTERS": []
            }
        }

        # 遍历 kms_alarm_model 数据并更新统计信息
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典
            sys_name = alarm_dict["sys_name"]
            level = alarm_dict["level"].upper()  # 将告警级别转换为大写
            found = False

            # 检查是否已经存在相同的 sys_name
            for item in level_sysname["level"][level]:
                if item['sys_name'] == sys_name:
                    item['count'] += 1
                    found = True
                    break
            # debug
            # print(level)
            # print(level_sysname[level])

            # 如果没有找到相同的 sys_name，则添加新的条目
            if not found:
                level_sysname["level"][level].append({'sys_name': sys_name, 'count': 1})

        # print(level_sysname["level"]["WARNING"])
        # print(level_sysname["level"]["MINOR"])
        # print(level_sysname["level"]["MAJOR"])
        # print(level_sysname["level"]["INFO"])
        # print(level_sysname["level"]["OHTERS"])

        # 打印结果
        # print(level_sysname)
        if level_sysname:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(level_sysname, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


@ns_kms_alarm.route('/getbymultiquerylevel2')
class AlarmMultiQLevel2Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_level2_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
        leveldata = api.payload

        sysname = leveldata['sys_name']
        devaddr = leveldata['dev_addr']
        level = leveldata['level']
        repeattimes = leveldata['repeat_times']
        # 获取分页请求信息
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 示例日期时间格式 2024-06-18 18:01:40.000000
        # 将日期字符串转换为 datetime 对象
        # start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
        # end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # --------------------------------------------------#
        # 初始化 level_sysname 字典结构
        level_sysname = {
            "WARNING": defaultdict(int),
            "MINOR": defaultdict(int),
            "MAJOR": defaultdict(int),
            "INFO": defaultdict(int),
            "CRITICAL": defaultdict(int)
        }

        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典

            sys_name = alarm_dict["sys_name"]
            # print(sys_name)
            # level = alarm_dict["level"].lower()  # 将告警级别转换为小写
            # level = alarm_dict["level"]
            # print(alarm_dict["level"].upper())
            level = alarm_dict["level"].upper()  # 将告警级别转换为小写
            level_sysname[level][sys_name] += 1
            # print(level_sysname[level][sys_name])
            # print(level_sysname[level])
        # ------------------------------------------------------#
        # debug
        alarm_dict_for_fields = []
        fieldssystem = []
        for alarm in kms_alarm:
            alarm_dict_for_fields = alarm.to_dict()
            if alarm_dict_for_fields["sys_name"] in fieldssystem:
                None
            else:
                fieldssystem.append(alarm_dict_for_fields["sys_name"])
                # print(alarm_dict["sys_name"])
            # for sys_name in alarm.to_dict()["sys_name"]:
            #     print("debug 系统名")
            #     print(sys_name)

        # 构建输出结构
        output_data = {
            "level2": [
                {"name": "WARNING", **level_sysname["WARNING"]},
                {"name": "MINOR", **level_sysname["MINOR"]},
                {"name": "MAJOR", **level_sysname["MAJOR"]},
                {"name": "INFO", **level_sysname["INFO"]},
                {"name": "CRITICAL", **level_sysname["CRITICAL"]}
            ],
            "fields": fieldssystem
        }

        # 打印结果
        print(output_data)
        if output_data:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(output_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


# @ns_kms_alarm.route('/getbymultiquerylevel3')
# class AlarmMultiQLevel3Resource(Resource):
#     @ns_kms_alarm.expect(kms_alarm_multi_query_model)
#     # @jwt_required()
#     @ns_kms_alarm.marshal_with(response_level3_model)
#     def post(self):
#         """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
#         leveldata = api.payload
#
#         sysname = leveldata['sys_name']
#         devaddr = leveldata['dev_addr']
#         level = leveldata['level']
#         repeattimes = leveldata['repeat_times']
#         # 获取分页请求信息
#         start_date_str = leveldata['start_date']
#         end_date_str = leveldata['end_date']
#
#         # 示例日期时间格式 2024-06-18 18:01:40.000000
#         # 将日期字符串转换为 datetime 对象
#         start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
#         end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
#
#         # 构建查询条件
#         filters = [
#             Zbfwb_kms_alarm.occurrence_time >= start_date,
#             Zbfwb_kms_alarm.occurrence_time <= end_date
#         ]
#         if devaddr:
#             filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
#         if sysname:
#             filters.append(Zbfwb_kms_alarm.sys_name == sysname)
#         if level:
#             filters.append(Zbfwb_kms_alarm.level == level)
#         if repeattimes:
#             filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)
#
#         # 查询并过滤数据
#         query = Zbfwb_kms_alarm.query.filter(and_(*filters))
#
#         # 计算总记录数
#         total_records = query.count()
#         # 获取记录
#         kms_alarm = query.all()
#
#         # 初始化 level_sysname 字典结构
#         levels = ["WARNING", "MINOR", "MAJOR", "INFO", "OTHERS"]
#         level_sysname = defaultdict(lambda: defaultdict(int))
#
#         # 遍历 kms_alarm_model 数据并更新统计信息
#         for alarm in kms_alarm:
#             alarm_dict = alarm.to_dict()  # 将实例转换为字典
#
#             sys_name = alarm_dict["sys_name"]
#             level = alarm_dict["level"].upper()  # 将告警级别转换为大写
#             level_sysname[sys_name][level] += 1
#
#         # 初始化二维数组，第一行为标题
#         output_data = [["product"] + levels]
#
#         # 构建二维数组数据
#         for sys_name, level_counts in level_sysname.items():
#             row = [sys_name] + [level_counts.get(level, 0) for level in levels]
#             output_data.append(row)
#
#         if output_data:
#             # return kms_alarm
#             # 使用 format_response 格式化返回结果
#             response_data = format_response(output_data, total_records, 1, "successfully")
#             return response_data
#         else:
#             response_data = format_response("[]", 0, 0, "no data")
#             return response_data


@ns_kms_alarm.route('/getbymultiquerylevel3')
class AlarmMultiQLevel3Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_level3_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13"""
        leveldata = api.payload

        sysname = leveldata['sys_name']
        devaddr = leveldata['dev_addr']
        level = leveldata['level']
        repeattimes = leveldata['repeat_times']
        # 获取分页请求信息
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 将日期字符串转换为 datetime 对象
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # 初始化 level_sysname 字典结构
        levels = ["WARNING", "MINOR", "MAJOR", "INFO", "CRITICAL"]
        level_sysname = defaultdict(lambda: defaultdict(int))

        # 遍历 kms_alarm_model 数据并更新统计信息
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典

            sys_name = alarm_dict["sys_name"]
            level = alarm_dict["level"].upper()  # 将告警级别转换为大写
            level_sysname[sys_name][level] += 1

        # 初始化二维数组，第一行为标题
        output_data = [["product"] + levels]

        # 构建二维数组数据
        for sys_name, level_counts in level_sysname.items():
            row = [sys_name] + [level_counts.get(level, 0) for level in levels]
            output_data.append(row)

        if output_data:
            # 使用 format_response 格式化返回结果
            response_data = format_response(output_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


@ns_kms_alarm.route('/getbymultiquerytrend1')
class AlarmMultiQsystrend1Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_query_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_trend1_model)
    def post(self):
        """多条件查询告警趋势分析信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
        leveldata = api.payload

        sysname = leveldata['sys_name']
        devaddr = leveldata['dev_addr']
        level = leveldata['level']
        repeattimes = leveldata['repeat_times']
        # 获取分页请求信息
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 示例日期时间格式 2024-06-18 18:01:40.000000
        # 将日期字符串转换为 datetime 对象
        # start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
        # end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sysname:
            filters.append(Zbfwb_kms_alarm.sys_name == sysname)
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # result_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
        # dates = set()
        #
        # for alarm in kms_alarm:
        #     alarm_dict = alarm.to_dict()  # 将实例转换为字典
        #
        #     sys_name = alarm_dict["sys_name"]
        #     level = alarm_dict["level"].upper()
        #     date = alarm_dict["occurrence_time"]
        #     result_dict[date][sys_name][level] += 1
        #     dates.add(date)
        #
        # # debug
        # print("debug1")
        # # print(dates)
        #
        # result_data = []
        # for date in sorted(dates):
        #     for sys_name in result_dict[date]:
        #         entry = {
        #             "product": sys_name,
        #             "WARNING": result_dict[date][sys_name].get("WARNING", 0),
        #             "MINOR": result_dict[date][sys_name].get("MINOR", 0),
        #             "MAJOR": result_dict[date][sys_name].get("MAJOR", 0),
        #             "INFO": result_dict[date][sys_name].get("INFO", 0),
        #             "OTHERS": result_dict[date][sys_name].get("OTHERS", 0),
        #             "date": date
        #         }
        #         result_data.append(entry)
        #
        # # debug
        # print("debug4")
        # # print(result_data)
        # # for result1 in result_data:
        # #     print(result1)

        # 获取独特的系统名称
        headers = list({alarm.to_dict()['sys_name'] for alarm in kms_alarm})
        result_data = []

        # 添加表头
        result_data.append(headers)

        levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'CRITICAL']
        result_data.append(levels)

        # 初始化一个字典来存储各个系统的告警计数
        counts = {sys_name: {level: 0 for level in levels} for sys_name in headers}

        # # 初始化一个字典来存储每个日期和系统名称的最后一次累加统计
        # last_row = {}

        # 初始化一个字典来存储每个日期和系统名称的告警计数
        daily_counts = {}

        # 处理每个告警记录，统计数据
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典
            sys_name = alarm_dict['sys_name']
            level = alarm_dict['level']
            occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')

            # # 更新计数
            # if level in counts[sys_name]:
            #     counts[sys_name][level] += 1

            # # 将数据按日期和系统名组织
            # row = [occurrence_time, sys_name] + [counts[sys_name][lvl] for lvl in levels]
            # result_data.append(row)

            # 如果当天的计数不存在，则初始化
            if (occurrence_time, sys_name) not in daily_counts:
                daily_counts[(occurrence_time, sys_name)] = {lvl: 0 for lvl in levels}

            # 更新当天的计数
            if level in daily_counts[(occurrence_time, sys_name)]:
                daily_counts[(occurrence_time, sys_name)][level] += 1

        #     # 将数据按日期和系统名组织
        #     key = (occurrence_time, sys_name)
        #     row = [occurrence_time, sys_name] + [counts[sys_name][lvl] for lvl in levels]
        #     last_row[key] = row
        #
        # # 将最后一次累加统计的数据加入 result_data
        # result_data.extend(last_row.values())

        # 将统计数据按日期和系统名组织
        for (date, sys_name), counts in daily_counts.items():
            row = [date, sys_name] + [counts[lvl] for lvl in levels]
            result_data.append(row)

        if result_data:
            # return kms_alarm
            # 使用 format_response 格式化返回结果
            response_data = format_response(result_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


# @ns_kms_alarm.route('/getbymultiquerytrend2')
# class AlarmMultiQsystrend2Resource(Resource):
#     @ns_kms_alarm.expect(kms_alarm_multi_sys_query_model)
#     # @jwt_required()
#     @ns_kms_alarm.marshal_with(response_trend1_model)
#     def post(self):
#         """多条件查询告警趋势分析信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
#         leveldata = api.payload
#
#         sys_names = leveldata['sys_name']
#         devaddr = leveldata['dev_addr']
#         level = leveldata['level']
#         repeattimes = leveldata['repeat_times']
#         start_date_str = leveldata['start_date']
#         end_date_str = leveldata['end_date']
#
#         # 将日期字符串转换为 datetime 对象
#         start_date = datetime.fromisoformat(start_date_str)
#         end_date = datetime.fromisoformat(end_date_str)
#
#         # 构建查询条件
#         filters = [
#             Zbfwb_kms_alarm.occurrence_time >= start_date,
#             Zbfwb_kms_alarm.occurrence_time <= end_date
#         ]
#         if devaddr:
#             filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
#         if sys_names:
#             filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
#         if level:
#             filters.append(Zbfwb_kms_alarm.level == level)
#         if repeattimes:
#             filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)
#
#         # 查询并过滤数据
#         query = Zbfwb_kms_alarm.query.filter(and_(*filters))
#
#         # 计算总记录数
#         total_records = query.count()
#         # 获取记录
#         kms_alarm = query.all()
#
#         # 获取独特的系统名称
#         headers = list({alarm.to_dict()['sys_name'] for alarm in kms_alarm})
#         result_data = []
#
#         # 添加表头
#         result_data.append(headers)
#
#         levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'OTHERS']
#         result_data.append(levels)
#
#         # 初始化一个字典来存储每个日期和系统名称的告警计数
#         daily_counts = {}
#
#         # 处理每个告警记录，统计数据
#         for alarm in kms_alarm:
#             alarm_dict = alarm.to_dict()  # 将实例转换为字典
#             sys_name = alarm_dict['sys_name']
#             level = alarm_dict['level']
#             occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')
#
#             # 如果当天的计数不存在，则初始化
#             if (occurrence_time, sys_name) not in daily_counts:
#                 daily_counts[(occurrence_time, sys_name)] = {lvl: 0 for lvl in levels}
#
#             # 更新当天的计数
#             if level in daily_counts[(occurrence_time, sys_name)]:
#                 daily_counts[(occurrence_time, sys_name)][level] += 1
#
#         # 将统计数据按日期和系统名组织，并按日期排序
#         sorted_daily_counts = sorted(daily_counts.items(), key=lambda x: x[0][0])
#
#         # # 将统计数据按日期和系统名组织
#         # for (date, sys_name), counts in daily_counts.items():
#         #     row = [date, sys_name] + [counts[lvl] for lvl in levels]
#         #     result_data.append(row)
#
#         for (date, sys_name), counts in sorted_daily_counts:
#             row = [date, sys_name] + [counts[lvl] for lvl in levels]
#             result_data.append(row)
#
#         if result_data:
#             # 使用 format_response 格式化返回结果
#             response_data = format_response(result_data, total_records, 1, "successfully")
#             return response_data
#         else:
#             response_data = format_response("[]", 0, 0, "no data")
#             return response_data


# @ns_kms_alarm.route('/getbymultiquerytrend2')
# class AlarmMultiQsystrend2Resource(Resource):
#     @ns_kms_alarm.expect(kms_alarm_multi_sys_query_model)
#     # @jwt_required()
#     @ns_kms_alarm.marshal_with(response_trend1_model)
#     def post(self):
#         """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13+点+247441"""  # 接口说明紧跟在函数后面
#         leveldata = api.payload
#
#         sys_names = leveldata['sys_name']
#         devaddr = leveldata['dev_addr']
#         level = leveldata['level']
#         repeattimes = leveldata['repeat_times']
#         # 获取分页请求信息
#         start_date_str = leveldata['start_date']
#         end_date_str = leveldata['end_date']
#
#         # 示例日期时间格式 2024-06-18 18:01:40.000000
#         # 将日期字符串转换为 datetime 对象
#         start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
#         end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
#
#         # 构建查询条件
#         filters = [
#             Zbfwb_kms_alarm.occurrence_time >= start_date,
#             Zbfwb_kms_alarm.occurrence_time <= end_date
#         ]
#         if devaddr:
#             filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
#         if sys_names:
#             filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
#         if level:
#             filters.append(Zbfwb_kms_alarm.level == level)
#         if repeattimes:
#             filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)
#
#         # 查询并过滤数据
#         query = Zbfwb_kms_alarm.query.filter(and_(*filters))
#
#         # 计算总记录数
#         total_records = query.count()
#         # 获取记录
#         kms_alarm = query.all()
#
#         # 获取独特的系统名称并保持顺序
#         headers = sys_names
#
#         result_data = []
#
#         # 添加表头
#         result_data.append(headers)
#
#         levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'OTHERS']
#         result_data.append(levels)
#
#         # 初始化一个字典来存储各个系统的告警计数
#         counts = {(sys_name, level): 0 for sys_name in headers for level in levels}
#
#         # 初始化一个字典来存储每天每个系统的告警计数
#         daily_counts = {}
#
#         # 处理每个告警记录，统计数据
#         for alarm in kms_alarm:
#             alarm_dict = alarm.to_dict()  # 将实例转换为字典
#             sys_name = alarm_dict['sys_name']
#             level = alarm_dict['level']
#             occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')
#
#             # 初始化当天的计数字典
#             if (occurrence_time, sys_name) not in daily_counts:
#                 daily_counts[(occurrence_time, sys_name)] = {lvl: 0 for lvl in levels}
#
#             # 更新当天计数
#             if level in daily_counts[(occurrence_time, sys_name)]:
#                 daily_counts[(occurrence_time, sys_name)][level] += 1
#
#         # 按日期排序
#         sorted_daily_counts = sorted(daily_counts.items(), key=lambda x: x[0][0])
#
#         # 将统计数据按日期和系统名组织
#         for date in sorted(set(date for date, _ in sorted_daily_counts)):
#             for sys_name in headers:
#                 counts_for_day_sys = daily_counts.get((date, sys_name), {lvl: 0 for lvl in levels})
#                 row = [date, sys_name] + [counts_for_day_sys[lvl] for lvl in levels]
#                 result_data.append(row)
#
#         if result_data:
#             # 使用 format_response 格式化返回结果
#             response_data = format_response(result_data, total_records, 1, "successfully")
#             return response_data
#         else:
#             response_data = format_response("[]", 0, 0, "no data")
#             return response_data

# @ns_kms_alarm.route('/getbymultiquerytrend2')
# class AlarmMultiQsystrend2Resource(Resource):
#     @ns_kms_alarm.expect(kms_alarm_multi_sys_query_model)
#     @ns_kms_alarm.marshal_with(response_trend1_model)
#     def post(self):
#         """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13+点+247441"""
#         leveldata = api.payload
#
#         sys_names = leveldata.get('sys_name', [])
#         devaddr = leveldata['dev_addr']
#         level = leveldata['level']
#         repeattimes = leveldata['repeat_times']
#         start_date_str = leveldata['start_date']
#         end_date_str = leveldata['end_date']
#
#         # 日期格式处理
#         start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S.%f')
#         end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S.%f')
#
#         # 构建查询条件
#         filters = [
#             Zbfwb_kms_alarm.occurrence_time >= start_date,
#             Zbfwb_kms_alarm.occurrence_time <= end_date
#         ]
#         if devaddr:
#             filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
#         if sys_names:  # 仅在 sys_names 非空时添加条件
#             filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
#         if level:
#             filters.append(Zbfwb_kms_alarm.level == level)
#         if repeattimes:
#             filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)
#
#         # 查询并获取记录
#         query = Zbfwb_kms_alarm.query.filter(and_(*filters))
#         total_records = query.count()
#         kms_alarm = query.all()
#
#         # 如果 sys_names 为空，则获取所有唯一的系统名称
#         if not sys_names:
#             unique_sys_names = {alarm.sys_name for alarm in kms_alarm}
#             headers = sorted(unique_sys_names)  # 可选：对系统名称进行排序
#         else:
#             headers = sys_names
#
#         levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'OTHERS']
#
#         # 初始化一个字典来存储每天每个系统的告警计数
#         date_counts = {sys_name: {} for sys_name in headers}
#
#         # 处理每个告警记录，统计数据
#         for alarm in kms_alarm:
#             alarm_dict = alarm.to_dict()
#             sys_name = alarm_dict['sys_name']
#             level = alarm_dict['level']
#             occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')
#
#             # 更新每天的计数
#             if sys_name in date_counts:
#                 if occurrence_time not in date_counts[sys_name]:
#                     date_counts[sys_name][occurrence_time] = {lvl: 0 for lvl in levels}
#                 date_counts[sys_name][occurrence_time][level] += 1
#
#         # 准备最终输出数据
#         result_data = []
#         result_data.append(headers)  # 系统名称
#         result_data.append(levels)  # 告警级别
#
#         # 获取所有日期
#         all_dates = sorted(set(date for counts in date_counts.values() for date in counts.keys()))
#
#         # 按日期生成结果
#         for date in all_dates:
#             for sys_name in headers:
#                 counts_for_day = date_counts.get(sys_name, {}).get(date, {lvl: 0 for lvl in levels})
#                 row = [date, sys_name] + [counts_for_day[lvl] for lvl in levels]
#                 result_data.append(row)
#
#         if result_data:
#             # 使用 format_response 格式化返回结果
#             response_data = format_response(result_data, total_records, 1, "successfully")
#             return response_data
#         else:
#             response_data = format_response("[]", 0, 0, "no data")
#             return response_data


# # 构造返回结果
# response_data = {
#     "message": {
#         "result": 1,
#         "result_text": "successfully",
#         "count": total_records,
#         "data": result_data
#     }
# }
#
# return response_data


@ns_kms_alarm.route('/getbymultiquerytrend2')
class AlarmMultiQsystrend2Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_sys_query_model)
    @ns_kms_alarm.marshal_with(response_trend1_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13"""
        leveldata = api.payload

        sys_names = leveldata.get('sys_name', [])
        devaddr = leveldata['dev_addr']
        level = leveldata['level']
        repeattimes = leveldata['repeat_times']
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 日期格式处理
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddr:
            filters.append(Zbfwb_kms_alarm.dev_addr == devaddr)
        if sys_names:  # 仅在 sys_names 非空时添加条件
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
        if level:
            filters.append(Zbfwb_kms_alarm.level == level)
        if repeattimes:
            filters.append(Zbfwb_kms_alarm.repeat_times == repeattimes)

        # 查询并获取记录
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))
        total_records = query.count()
        kms_alarm = query.all()

        # 如果 sys_names 为空，则获取所有唯一的系统名称
        if not sys_names:
            unique_sys_names = {alarm.sys_name for alarm in kms_alarm}
            headers = sorted(unique_sys_names)  # 可选：对系统名称进行排序
        else:
            headers = sys_names

        # levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'OTHERS']
        levels = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'CRITICAL']

        # 初始化一个字典来存储每天每个系统的告警计数
        date_counts = {sys_name: {} for sys_name in headers}

        # 处理每个告警记录，统计数据
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()
            sys_name = alarm_dict['sys_name']
            level = alarm_dict['level']
            occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')

            # 更新每天的计数
            if sys_name in date_counts:
                if occurrence_time not in date_counts[sys_name]:
                    date_counts[sys_name][occurrence_time] = {lvl: 0 for lvl in levels}
                date_counts[sys_name][occurrence_time][level] += 1

        # 准备最终输出数据
        result_data = []
        result_data.append(headers)  # 系统名称
        result_data.append(levels)  # 告警级别

        # 获取所有日期
        all_dates = sorted(set(date for counts in date_counts.values() for date in counts.keys()))

        # 按日期生成结果
        for date in all_dates:
            for sys_name in headers:
                counts_for_day = date_counts.get(sys_name, {}).get(date, {lvl: 0 for lvl in levels})
                row = [date, sys_name] + [counts_for_day[lvl] for lvl in levels]
                result_data.append(row)

        if result_data:
            # 使用 format_response 格式化返回结果
            response_data = format_response(result_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


# @ns_kms_alarm.route('/getbymultiquerytypelist')
# class AlarmMultiQtypelistResource(Resource):
#     @ns_kms_alarm.expect(kms_alarm_type_sts_model)
#     @ns_kms_alarm.marshal_with(response_type_sts_model)
#     def post(self):
#         """统计类型种类和数量 类型取值4种 sys_name dev_addr repeat_times level 日期格式：2024-06-18 18:10:13"""
#         typedata = api.payload
#         query_type = typedata.get("type")
#
#         # 确保传入的查询类型合法
#         if query_type not in ["sys_name", "dev_addr", "repeat_times", "level"]:
#             response_data = format_response([], 0, -1, "Invalid query type provided.")
#             return response_data
#
#         # 根据查询类型构建不同的查询语句
#         if query_type == "sys_name":
#             query = db.session.query(
#                 Zbfwb_kms_alarm.sys_name,
#                 db.func.count(Zbfwb_kms_alarm.sys_name).label('count')
#             ).group_by(Zbfwb_kms_alarm.sys_name)
#         elif query_type == "dev_addr":
#             query = db.session.query(
#                 Zbfwb_kms_alarm.dev_addr,
#                 db.func.count(Zbfwb_kms_alarm.dev_addr).label('count')
#             ).group_by(Zbfwb_kms_alarm.dev_addr)
#         elif query_type == "repeat_times":
#             query = db.session.query(
#                 Zbfwb_kms_alarm.repeat_times,
#                 db.func.count(Zbfwb_kms_alarm.repeat_times).label('count')
#             ).group_by(Zbfwb_kms_alarm.repeat_times)
#         elif query_type == "level":
#             query = db.session.query(
#                 Zbfwb_kms_alarm.level,
#                 db.func.count(Zbfwb_kms_alarm.level).label('count')
#             ).group_by(Zbfwb_kms_alarm.level)
#
#         # 执行查询并获取结果
#         result = query.all()
#
#         # 将结果数据转化为字典列表
#         data = [{"type": item[0], "count": item[1]} for item in result]
#
#         if data:
#             # 使用 format_response 格式化返回结果
#             response_data = format_response(data, len(data), 1, "successfully")
#             return response_data
#         else:
#             response_data = format_response("[]", 0, 0, "no data")
#             return response_data


@ns_kms_alarm.route('/getbymultiquerytypelist')
class AlarmMultiQtypelistResource(Resource):
    @ns_kms_alarm.expect(kms_alarm_type_sts_model)
    @ns_kms_alarm.marshal_with(response_type_sts_model)
    def post(self):
        """统计类型种类和数量 类型取值4种 sys_name dev_addr repeat_times level 日期格式：2024-06-18 18:10:13"""
        typedata = request.json  # 获取传入的JSON数据
        query_type = typedata.get("type")
        start_date_str = typedata.get("start_date")
        end_date_str = typedata.get("end_date")

        # 确保传入的查询类型合法
        if query_type not in ["sys_name", "dev_addr", "repeat_times", "level"]:
            response_data = format_response([], 0, -1, "Invalid query type provided.")
            return response_data

        # 尝试将字符串日期转换为 datetime 对象
        try:
            start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            response_data = format_response([], 0, -1, "Invalid date format. Expected: YYYY-MM-DD HH:MM:SS")
            return response_data

        # 构建基本的查询语句，并增加时间过滤
        if query_type == "sys_name":
            query = db.session.query(
                Zbfwb_kms_alarm.sys_name,
                db.func.count(Zbfwb_kms_alarm.sys_name).label('count')
            ).filter(
                and_(Zbfwb_kms_alarm.occurrence_time >= start_date, Zbfwb_kms_alarm.occurrence_time <= end_date)
            ).group_by(Zbfwb_kms_alarm.sys_name)
        elif query_type == "dev_addr":
            query = db.session.query(
                Zbfwb_kms_alarm.dev_addr,
                db.func.count(Zbfwb_kms_alarm.dev_addr).label('count')
            ).filter(
                and_(Zbfwb_kms_alarm.occurrence_time >= start_date, Zbfwb_kms_alarm.occurrence_time <= end_date)
            ).group_by(Zbfwb_kms_alarm.dev_addr)
        elif query_type == "repeat_times":
            query = db.session.query(
                Zbfwb_kms_alarm.repeat_times,
                db.func.count(Zbfwb_kms_alarm.repeat_times).label('count')
            ).filter(
                and_(Zbfwb_kms_alarm.occurrence_time >= start_date, Zbfwb_kms_alarm.occurrence_time <= end_date)
            ).group_by(Zbfwb_kms_alarm.repeat_times)
        elif query_type == "level":
            query = db.session.query(
                Zbfwb_kms_alarm.level,
                db.func.count(Zbfwb_kms_alarm.level).label('count')
            ).filter(
                and_(Zbfwb_kms_alarm.occurrence_time >= start_date, Zbfwb_kms_alarm.occurrence_time <= end_date)
            ).group_by(Zbfwb_kms_alarm.level)

        # 执行查询并获取结果
        result = query.all()

        # 将结果数据转化为字典列表
        data = [{"type": item[0], "count": item[1]} for item in result]

        if data:
            # 使用 format_response 格式化返回结果
            response_data = format_response(data, len(data), 3, "successfully")
            return response_data
        else:
            response_data = format_response([], 0, 30, "no data")
            return response_data


@ns_kms_alarm.route('/getbymultiquerytrend3')
class AlarmMultiQsystrend3Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_sys_query1_model)
    @ns_kms_alarm.marshal_with(response_trend1_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13"""
        leveldata = api.payload

        sys_names = leveldata.get('sys_name', [])
        devaddrs = leveldata.get('dev_addr', [])
        levels = leveldata.get('level', [])
        repeat_times = leveldata.get('repeat_times', [])
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 日期格式处理
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if devaddrs:
            filters.append(Zbfwb_kms_alarm.dev_addr.in_(devaddrs))
        if sys_names:
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
        if levels:
            filters.append(Zbfwb_kms_alarm.level.in_(levels))
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))

        # 查询并获取记录
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))
        total_records = query.count()
        kms_alarm = query.all()

        # 如果 sys_names 为空，则获取所有唯一的系统名称
        if not sys_names:
            unique_sys_names = {alarm.sys_name for alarm in kms_alarm}
            headers = sorted(unique_sys_names)  # 可选：对系统名称进行排序
        else:
            headers = sys_names

        level_list = ['WARNING', 'MINOR', 'MAJOR', 'INFO', 'CRITICAL']

        # 初始化一个字典来存储每天每个系统的告警计数
        date_counts = {sys_name: {} for sys_name in headers}

        # 处理每个告警记录，统计数据
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()
            sys_name = alarm_dict['sys_name']
            level = alarm_dict['level']
            occurrence_time = alarm_dict['occurrence_time'].strftime('%Y-%m-%d')

            # 更新每天的计数
            if sys_name in date_counts:
                if occurrence_time not in date_counts[sys_name]:
                    date_counts[sys_name][occurrence_time] = {lvl: 0 for lvl in level_list}
                date_counts[sys_name][occurrence_time][level] += 1

        # 准备最终输出数据
        result_data = []
        result_data.append(headers)  # 系统名称
        result_data.append(level_list)  # 告警级别

        # 获取所有日期
        all_dates = sorted(set(date for counts in date_counts.values() for date in counts.keys()))

        # 按日期生成结果
        for date in all_dates:
            for sys_name in headers:
                counts_for_day = date_counts.get(sys_name, {}).get(date, {lvl: 0 for lvl in level_list})
                row = [date, sys_name] + [counts_for_day[lvl] for lvl in level_list]
                result_data.append(row)

        if result_data:
            # 使用 format_response 格式化返回结果
            response_data = format_response(result_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


@ns_kms_alarm.route('/getbymultiquerylevel4')
class AlarmMultiQLevel4Resource(Resource):
    @ns_kms_alarm.expect(kms_alarm_multi_sys_query1_model)
    # @jwt_required()
    @ns_kms_alarm.marshal_with(response_level3_model)
    def post(self):
        """多条件查询告警级别信息 日期格式：2024-06-18 18:10:13"""
        leveldata = api.payload

        sys_names = leveldata.get('sys_name', [])
        dev_addrs = leveldata.get('dev_addr', [])
        levels = leveldata.get('level', [])
        repeat_times = leveldata.get('repeat_times', [])
        start_date_str = leveldata['start_date']
        end_date_str = leveldata['end_date']

        # 将日期字符串转换为 datetime 对象
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

        # 构建查询条件
        filters = [
            Zbfwb_kms_alarm.occurrence_time >= start_date,
            Zbfwb_kms_alarm.occurrence_time <= end_date
        ]
        if dev_addrs:
            filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))
        if sys_names:
            filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
        if levels:
            filters.append(Zbfwb_kms_alarm.level.in_(levels))
        if repeat_times:
            filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))

        # 查询并过滤数据
        query = Zbfwb_kms_alarm.query.filter(and_(*filters))

        # 计算总记录数
        total_records = query.count()
        # 获取记录
        kms_alarm = query.all()

        # 初始化 level_sysname 字典结构
        level_list = ["WARNING", "MINOR", "MAJOR", "INFO", "CRITICAL"]
        level_sysname = defaultdict(lambda: defaultdict(int))

        # 遍历 kms_alarm_model 数据并更新统计信息
        for alarm in kms_alarm:
            alarm_dict = alarm.to_dict()  # 将实例转换为字典

            sys_name = alarm_dict["sys_name"]
            level = alarm_dict["level"].upper()  # 将告警级别转换为大写
            level_sysname[sys_name][level] += 1

        # 初始化二维数组，第一行为标题
        output_data = [["product"] + level_list]

        # 构建二维数组数据
        for sys_name, level_counts in level_sysname.items():
            row = [sys_name] + [level_counts.get(level, 0) for level in level_list]
            output_data.append(row)

        if output_data:
            # 使用 format_response 格式化返回结果
            response_data = format_response(output_data, total_records, 1, "successfully")
            return response_data
        else:
            response_data = format_response("[]", 0, 0, "no data")
            return response_data


# 定义数据条数统计查询资源
# 按照五级告警统计数据(时间范围可以输入)
@ns_kms_alarm.route('/postdashbaordlevel')
class KmsDashboardLevel(Resource):
    @ns_kms_alarm.expect(kms_alarm_dashboard_query_model)
    @ns_kms_alarm.marshal_with(response_dashboard_level_model)
    def post(self):
        """按照五级告警统计数据(时间范围可以输入)"""
        try:
            # 获取传入的查询条件
            filters = []
            requestdata = request.json

            # 根据输入查询数据，并且按照 告警类别统计和输出
            # ["CRITICAL", "MINOR", "MAJOR", "WARNING", "INFO"]

            # 数据查询
            sys_names = requestdata.get('sys_name', [])
            dev_addrs = requestdata.get('dev_addr', [])
            levels = requestdata.get('level', [])
            repeat_times = requestdata.get('repeat_times', [])
            start_date_str = requestdata['start_date']
            end_date_str = requestdata['end_date']

            # 将日期字符串转换为 datetime 对象
            start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

            # 构建查询条件
            filters = [
                Zbfwb_kms_alarm.occurrence_time >= start_date,
                Zbfwb_kms_alarm.occurrence_time <= end_date
            ]
            if dev_addrs:
                filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))
            if sys_names:
                filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
            if levels:
                filters.append(Zbfwb_kms_alarm.level.in_(levels))
            if repeat_times:
                filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))

            # 查询并过滤数据
            query = Zbfwb_kms_alarm.query.filter(and_(*filters))

            # 处理逻辑
            # 定义告警级别类别
            alarm_levels = ["CRITICAL", "MINOR", "MAJOR", "WARNING", "INFO"]

            # 初始化各告警类别的计数
            level_counts = {level: 0 for level in alarm_levels}

            # 遍历查询结果，统计每个告警级别的数量
            for alarm in query:
                if alarm.level in level_counts:
                    level_counts[alarm.level] += 1

            # 构建响应数据
            response_data = {
                "message": {
                    "result": 4,  # 查询成功
                    "result_text": "查询成功",
                    "count": query.count(),  # 返回告警记录的数量
                    "data": {
                        "xAxis": {
                            "type": "category",
                            "data": alarm_levels,  # 告警类别 ["CRITICAL", "MINOR", "MAJOR", "WARNING", "INFO"]
                        },
                        "yAxis": {
                            "type": "value",
                        },
                        "series": {
                            "data": [str(level_counts[level]) for level in alarm_levels],  # 告警数量
                            "type": "bar",
                        }
                    }
                }
            }

            # 返回封装好的响应模型，状态码200
            return response_data, 200

        except Exception as e:
            # 捕获异常并准备异常响应数据
            response_data = {
                "message": {
                    "result": 40,  # 查询异常
                    "result_text": f"查询异常: {str(e)}",
                    "count": 0,
                    "data": []
                }
            }

            # 返回封装好的异常响应模型，状态码201
            return response_data, 201


# 定义数据条数统计查询资源
# 统计sys_name 每个取值的数量
@ns_kms_alarm.route('/postdashbaordappcount')
class KmsDashboardAppcount(Resource):
    @ns_kms_alarm.expect(kms_alarm_dashboard_query_model)
    @ns_kms_alarm.marshal_with(response_dashboard_app_model)
    def post(self):
        """统计sys_name 每个取值的数量"""
        try:
            # 获取传入的查询条件
            filters = []
            requestdata = request.json

            # 数据查询
            sys_names = requestdata.get('sys_name', [])
            dev_addrs = requestdata.get('dev_addr', [])
            levels = requestdata.get('level', [])
            repeat_times = requestdata.get('repeat_times', [])
            start_date_str = requestdata['start_date']
            end_date_str = requestdata['end_date']

            # 将日期字符串转换为 datetime 对象
            start_date = datetime.strptime(start_date_str, '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(end_date_str, '%Y-%m-%d %H:%M:%S')

            # 构建查询条件
            filters = [
                Zbfwb_kms_alarm.occurrence_time >= start_date,
                Zbfwb_kms_alarm.occurrence_time <= end_date
            ]
            if dev_addrs:
                filters.append(Zbfwb_kms_alarm.dev_addr.in_(dev_addrs))
            if sys_names:
                filters.append(Zbfwb_kms_alarm.sys_name.in_(sys_names))
            if levels:
                filters.append(Zbfwb_kms_alarm.level.in_(levels))
            if repeat_times:
                filters.append(Zbfwb_kms_alarm.repeat_times.in_(repeat_times))

            # 查询并过滤数据
            query = Zbfwb_kms_alarm.query.filter(and_(*filters))

            # 剩余逻辑
            # 对sys_name进行分组统计数量
            grouped_query = query.with_entities(
                Zbfwb_kms_alarm.sys_name,
                db.func.count(Zbfwb_kms_alarm.sys_name).label('count')
            ).group_by(Zbfwb_kms_alarm.sys_name).all()

            # 准备 xAxis 和 series 数据
            xAxis_data = [item[0] for item in grouped_query]  # sys_name 取值
            series_data = [item[1] for item in grouped_query]  # sys_name 对应的数量

            # 构建响应数据
            response_data = {
                "message": {
                    "result": 5,  # 查询成功
                    "result_text": "查询成功",
                    "count": len(xAxis_data),  # 返回的数据条数
                    "data": {
                        "xAxis": {
                            "type": "category",
                            "data": xAxis_data
                        },
                        "yAxis": {
                            "type": "value"
                        },
                        "series": {
                            "data": series_data,
                            "type": "bar"
                        }
                    }
                }
            }

            # 返回封装好的响应模型，状态码200
            return response_data, 200

        except Exception as e:
            # 捕获异常并准备异常响应数据
            response_data = {
                "message": {
                    "result": 50,  # 查询异常
                    "result_text": f"查询异常: {str(e)}",
                    "count": 0,
                    "data": []
                }
            }

            # 返回封装好的异常响应模型，状态码201
            return response_data, 201
